package com.huhao.wshare.Dynamic;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SnapHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import static com.huhao.wshare.Config.DYNAMIC_API;
import static com.huhao.wshare.Config.RELEASE_DYNAMIC_API;

import com.bumptech.glide.Glide;
import com.huhao.wshare.MainActivity;
import com.huhao.wshare.R;
import com.huhao.wshare.Refreshable;

public class DynamicFragment extends Fragment implements Refreshable, DynamicAdapter.OnImageStateChangeListener, ZoomedImageAdapter.OnImageCloseListener {

    private static final int PAGE_SIZE = 10;
    private RecyclerView rvDynamics;
    private DynamicAdapter dynamicAdapter;
    private List<DynamicItem> dynamicList = new ArrayList<>();
    private int currentPage = 0;
    private boolean isLastPage = false;
    private OkHttpClient client = new OkHttpClient();
    private ImageView ivAvatar;
    private ImageView ivBackground;
    private TextView tvName;
    private RecyclerView rvZoomedImages;
    private List<String> currentImageUrls = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dynamic, container, false);
        ivAvatar = view.findViewById(R.id.ivAvatar);
        ivBackground = view.findViewById(R.id.background_image);
        tvName = view.findViewById(R.id.tvName);
        rvZoomedImages = view.findViewById(R.id.rvZoomedImages);
        LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false);
        rvZoomedImages.setLayoutManager(layoutManager);

        // 添加 PagerSnapHelper 确保滑动对齐
        SnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(rvZoomedImages);

        initViews(view);
        loadInitialData();
        loadUserInfoFromSharedPreferences();
        rvZoomedImages.setOnClickListener(v -> {
            rvZoomedImages.setVisibility(View.GONE);
            if (getActivity() instanceof MainActivity) {
                ((MainActivity) getActivity()).showBottomNavigation();
            }
        });
        return view;
    }
    @Override
    public void onImageOpened() {
        if (getActivity() instanceof MainActivity) {
            ((MainActivity) getActivity()).hideBottomNavigation();
            ((MainActivity) getActivity()).setSwipeRefreshEnabled(false);
        }
    }

    @Override
    public void onImageClosed() {
        if (getActivity() instanceof MainActivity) {
            ((MainActivity) getActivity()).showBottomNavigation();
            ((MainActivity) getActivity()).setSwipeRefreshEnabled(true);
        }
    }

    @Override
    public void onImageClose() {
        rvZoomedImages.setVisibility(View.GONE);
        if (getActivity() instanceof MainActivity) {
            ((MainActivity) getActivity()).showBottomNavigation();
            ((MainActivity) getActivity()).setSwipeRefreshEnabled(true);
        }
    }


    private void loadUserInfoFromSharedPreferences() {
        SharedPreferences sp = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
        String username = sp.getString("username", "用户名");
        String avatarUrl = sp.getString("avatar", null);
        String bkImgUrl = sp.getString("bkImg", null);

        // 更新用户名
        tvName.setText(username);

        // 更新头像
        if (avatarUrl != null && !avatarUrl.isEmpty() && !avatarUrl.equals("null")) {
            Glide.with(this).load(avatarUrl).into(ivAvatar);
        } else {
            String gender = sp.getString("gender", "man");
            if ("man".equals(gender)) {
                ivAvatar.setImageResource(R.drawable.default_avatar_man);
            } else if ("woman".equals(gender)) {
                ivAvatar.setImageResource(R.drawable.default_avatar_woman);
            } else {
                ivAvatar.setImageResource(R.drawable.default_avatar_man);
            }
        }

        // 更新背景图
        if (bkImgUrl != null && !bkImgUrl.isEmpty() && !bkImgUrl.equals("null")) {
            Glide.with(this).load(bkImgUrl).into(ivBackground);
        } else {
            ivBackground.setImageResource(R.drawable.default_background);
        }
    }

    private void initViews(View view) {
        rvDynamics = view.findViewById(R.id.rvDynamics);
        // 更新DynamicAdapter的构造函数调用，添加所有监听器
        dynamicAdapter = new DynamicAdapter(requireContext(), dynamicList, (imageUrls, position) -> {
            currentImageUrls = imageUrls;
            rvZoomedImages.setAdapter(new ZoomedImageAdapter(requireContext(), imageUrls, this));
            if (rvZoomedImages.getLayoutManager() instanceof LinearLayoutManager) {
                ((LinearLayoutManager) rvZoomedImages.getLayoutManager()).scrollToPositionWithOffset(position, 0);
            }
            rvZoomedImages.setVisibility(View.VISIBLE);
            if (getActivity() instanceof MainActivity) {
                ((MainActivity) getActivity()).hideBottomNavigation();
            }
        }, this, (dynamicId, position, isLiked) -> {
            // 实现点赞功能
            likeDynamic(dynamicId, position, isLiked);
        }, (dynamicId, position, commentContent) -> {
            // 实现评论发送功能
            sendComment(dynamicId, position, commentContent);
        }, (commentId, dynamicPosition, commentPosition) -> {
            // 实现评论删除功能
            deleteComment(commentId, dynamicPosition, commentPosition);
        });
        rvDynamics.setLayoutManager(new LinearLayoutManager(requireContext()));
        rvDynamics.setAdapter(dynamicAdapter);
    }

    // 实现评论发送功能
    private void sendComment(int dynamicId, int position, String commentContent) {
        String token = getToken();
        if (token == null) {
            Toast.makeText(requireContext(), "未获取到 token", Toast.LENGTH_SHORT).show();
            return;
        }

        String url = RELEASE_DYNAMIC_API + "/" + dynamicId + "/comment";

        // 构造请求体
        JSONObject requestBody = new JSONObject();
        try {
            requestBody.put("content", commentContent);
        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(requireContext(), "构建请求失败", Toast.LENGTH_SHORT).show();
            return;
        }

        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + token)
                .post(okhttp3.RequestBody.create(requestBody.toString(), MediaType.parse("application/json")))
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                new Handler(Looper.getMainLooper()).post(() ->
                        Toast.makeText(requireContext(), "评论发送失败，请重试", Toast.LENGTH_SHORT).show()
                );
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                new Handler(Looper.getMainLooper()).post(() -> {
                    if (response.isSuccessful()) {
                        try {
                            String responseData = response.body().string();
                            JSONObject jsonResponse = new JSONObject(responseData);
                            int code = jsonResponse.getInt("code");

                            if (code == 200) {
                                // 解析返回的评论数据
                                JSONObject commentData = jsonResponse.getJSONObject("data");
                                int commentId = commentData.getInt("id");

                                JSONObject authorJson = commentData.getJSONObject("author");
                                int authorId = authorJson.getInt("id");
                                String username = authorJson.getString("username");
                                String avatar = authorJson.optString("avatar", null);

                                String content = commentData.getString("content");
                                String createTime = commentData.getString("createTime");

                                // 获取当前用户的完整信息
                                SharedPreferences sp = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
                                String gender = sp.getString("gender", "man");
                                String remark = sp.getString("remark", null);
                                String signs = sp.getString("signs", null);

                                Author commentAuthor = new Author(authorId, username, avatar, gender, remark, signs);
                                Comment newComment = new Comment(commentId, commentAuthor, content, createTime);

                                // 更新UI
                                DynamicItem item = dynamicList.get(position);
                                List<Comment> updatedComments = new ArrayList<>(item.getComments());
                                updatedComments.add(newComment);

                                DynamicItem updatedItem = item.updateComments(updatedComments);
                                dynamicList.set(position, updatedItem);
                                dynamicAdapter.notifyItemChanged(position);

                                Toast.makeText(requireContext(), "评论发送成功", Toast.LENGTH_SHORT).show();
                            } else {
                                String message = jsonResponse.optString("message", "评论发送失败");
                                Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(requireContext(), "解析响应失败", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(requireContext(), "评论发送失败，请重试", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    // 实现点赞功能
    private void likeDynamic(int dynamicId, int position, boolean isLiked) {
        String token = getToken();
        if (token == null) {
            Toast.makeText(requireContext(), "未获取到 token", Toast.LENGTH_SHORT).show();
            return;
        }

        String url = RELEASE_DYNAMIC_API + "/" + dynamicId + "/like";
        Request.Builder requestBuilder = new Request.Builder().url(url);

        // 根据当前点赞状态决定是点赞还是取消点赞
        if (isLiked) {
            // 取消点赞
            requestBuilder.delete();
        } else {
            // 点赞
            requestBuilder.post(okhttp3.RequestBody.create(new byte[0])); // 空body
        }

        requestBuilder.addHeader("Authorization", "Bearer " + token);

        client.newCall(requestBuilder.build()).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                new Handler(Looper.getMainLooper()).post(() ->
                        Toast.makeText(requireContext(), "操作失败，请重试", Toast.LENGTH_SHORT).show()
                );
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                new Handler(Looper.getMainLooper()).post(() -> {
                    if (response.isSuccessful()) {
                        try {
                            // 更新UI状态
                            DynamicItem item = dynamicList.get(position);
                            boolean newLikedStatus = !isLiked;

                            // 更新点赞用户列表
                            List<Author> newLikers = new ArrayList<>(item.getLikers());
                            if (newLikedStatus) {
                                // 添加当前用户到点赞列表
                                SharedPreferences sp = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
                                int userId = sp.getInt("id", -1);
                                String username = sp.getString("username", "我");
                                String avatar = sp.getString("avatar", null);
                                String gender = sp.getString("gender", "man");
                                String remark = sp.getString("remark", null);
                                String signs = sp.getString("signs", null);

                                Author currentUser = new Author(userId, username, avatar, gender, remark, signs);
                                newLikers.add(currentUser);
                            } else {
                                // 从点赞列表中移除当前用户
                                SharedPreferences sp = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
                                int userId = sp.getInt("id", -1);
                                newLikers.removeIf(author -> author.getId() == userId);
                            }

                            // 创建更新后的DynamicItem
                            DynamicItem updatedItem = item.updateLikeStatus(newLikedStatus, newLikers);
                            dynamicList.set(position, updatedItem);
                            dynamicAdapter.notifyItemChanged(position);
                        } catch (Exception e) {
                            Toast.makeText(requireContext(), "解析响应失败", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(requireContext(), "操作失败，请重试", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    // 添加删除评论功能
    private void deleteComment(int commentId, int dynamicPosition, int commentPosition) {
        String token = getToken();
        if (token == null) {
            Toast.makeText(requireContext(), "未获取到 token", Toast.LENGTH_SHORT).show();
            return;
        }

        String url = RELEASE_DYNAMIC_API + "/comments/" + commentId;

        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + token)
                .delete()
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                new Handler(Looper.getMainLooper()).post(() ->
                        Toast.makeText(requireContext(), "删除评论失败，请重试", Toast.LENGTH_SHORT).show()
                );
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                new Handler(Looper.getMainLooper()).post(() -> {
                    if (response.isSuccessful()) {
                        try {
                            String responseData = response.body().string();
                            JSONObject jsonResponse = new JSONObject(responseData);
                            int code = jsonResponse.getInt("code");

                            if (code == 200) {
                                // 更新UI
                                DynamicItem item = dynamicList.get(dynamicPosition);
                                List<Comment> updatedComments = new ArrayList<>(item.getComments());
                                updatedComments.remove(commentPosition);

                                DynamicItem updatedItem = item.updateComments(updatedComments);
                                dynamicList.set(dynamicPosition, updatedItem);
                                dynamicAdapter.notifyItemChanged(dynamicPosition);

                                Toast.makeText(requireContext(), "评论删除成功", Toast.LENGTH_SHORT).show();
                            } else {
                                String message = jsonResponse.optString("message", "删除评论失败");
                                Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(requireContext(), "解析响应失败", Toast.LENGTH_SHORT).show();
                        }
                    } else if (response.code() == 403) {
                        Toast.makeText(requireContext(), "只有评论作者或动态发布者才能删除该评论", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(requireContext(), "删除评论失败，请重试", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }


    private void loadInitialData() {
        currentPage = 0;
        isLastPage = false;
        dynamicList.clear();
        fetchData(currentPage);
        loadUserInfoFromSharedPreferences();
    }

    @Override
    public void refresh() {
        loadInitialData();
    }

    private void fetchData(int page) {
        String token = getToken();
        if (token == null) {
            Toast.makeText(requireContext(), "未获取到 token", Toast.LENGTH_SHORT).show();
            return;
        }

        String url = DYNAMIC_API + "?page=" + page + "&size=" + PAGE_SIZE;
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + token)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                new Handler(Looper.getMainLooper()).post(() -> {
                    Toast.makeText(requireContext(), "网络错误，请稍后重试", Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    try {
                        JSONObject jsonResponse = new JSONObject(responseData);
                        int code = jsonResponse.getInt("code");
                        if (code == 200) {
                            JSONObject data = jsonResponse.getJSONObject("data");
                            JSONArray content = data.getJSONArray("content");
                            List<DynamicItem> newData = parseDynamicItems(content);
                            isLastPage = data.getBoolean("last");

                            new Handler(Looper.getMainLooper()).post(() -> {
                                dynamicList.addAll(newData);
                                dynamicAdapter.notifyDataSetChanged();
                            });
                        }
                    } catch (JSONException e) {
                        new Handler(Looper.getMainLooper()).post(() -> {
                            Toast.makeText(requireContext(), "解析数据失败", Toast.LENGTH_SHORT).show();
                        });
                    }
                } else {
                    new Handler(Looper.getMainLooper()).post(() -> {
                        Toast.makeText(requireContext(), "获取动态失败", Toast.LENGTH_SHORT).show();
                    });
                }
            }
        });
    }

    public static List<DynamicItem> parseDynamicItems(JSONArray content) throws JSONException {
        List<DynamicItem> items = new ArrayList<>();
        for (int i = 0; i < content.length(); i++) {
            JSONObject itemJson = content.getJSONObject(i);
            int id = itemJson.optInt("id", 0);

            JSONObject authorJson = itemJson.optJSONObject("author");
            int authorId = 0;
            String username = "";
            String avatar = null;
            String gender = "empty";
            String remark = "";
            String signs = ""; // 新增signs字段
            if (authorJson != null) {
                authorId = authorJson.optInt("id", 0);
                username = authorJson.optString("username", "");
                avatar = authorJson.optString("avatar", null);
                gender = authorJson.optString("gender", "empty");
                remark = authorJson.optString("remark", "");
                signs = authorJson.optString("signs", ""); // 解析signs字段
            }
            // 修复构造函数调用，添加signs参数
            Author author = new Author(authorId, username, avatar, gender, remark, signs);

            String textContent = itemJson.optString("textContent", "");

            JSONArray imageUrlsJson = itemJson.optJSONArray("imageUrls");
            List<String> imageUrls = new ArrayList<>();
            if (imageUrlsJson != null) {
                for (int j = 0; j < imageUrlsJson.length(); j++) {
                    String imageUrl = imageUrlsJson.optString(j);
                    if (imageUrl != null && !imageUrl.isEmpty()) {
                        imageUrls.add(imageUrl);
                    }
                }
            }

            String video = itemJson.optString("video", null);
            String createTime = itemJson.optString("createTime", "");

            // 修改likers解析逻辑，从字符串列表改为Author对象列表
            JSONArray likersJson = itemJson.optJSONArray("likers");
            List<Author> likers = new ArrayList<>(); // 改为Author列表
            if (likersJson != null) {
                for (int k = 0; k < likersJson.length(); k++) {
                    JSONObject likerJson = likersJson.optJSONObject(k);
                    if (likerJson != null) {
                        int likerId = likerJson.optInt("id", 0);
                        String likerUsername = likerJson.optString("username", "");
                        String likerAvatar = likerJson.optString("avatar", null);
                        String likerGender = likerJson.optString("gender", "empty");
                        String likerRemark = likerJson.optString("remark", "");
                        String likerSigns = likerJson.optString("signs", ""); // 解析signs字段
                        // 修复构造函数调用，添加signs参数
                        Author likerAuthor = new Author(likerId, likerUsername, likerAvatar, likerGender, likerRemark, likerSigns);
                        likers.add(likerAuthor);
                    }
                }
            }

            // 修改comments解析逻辑，从字符串列表改为Comment对象列表
            JSONArray commentsJson = itemJson.optJSONArray("comments");
            List<Comment> comments = new ArrayList<>(); // 改为Comment列表
            if (commentsJson != null) {
                for (int l = 0; l < commentsJson.length(); l++) {
                    JSONObject commentJson = commentsJson.optJSONObject(l);
                    if (commentJson != null) {
                        int commentId = commentJson.optInt("id", 0);

                        // 解析评论作者
                        JSONObject commentAuthorJson = commentJson.optJSONObject("author");
                        int commentAuthorId = 0;
                        String commentUsername = "";
                        String commentAvatar = null;
                        String commentGender = "empty";
                        String commentRemark = "";
                        String commentSigns = "";
                        if (commentAuthorJson != null) {
                            commentAuthorId = commentAuthorJson.optInt("id", 0);
                            commentUsername = commentAuthorJson.optString("username", "");
                            commentAvatar = commentAuthorJson.optString("avatar", null);
                            commentGender = commentAuthorJson.optString("gender", "empty");
                            commentRemark = commentAuthorJson.optString("remark", "");
                            commentSigns = commentAuthorJson.optString("signs", "");
                        }
                        Author commentAuthor = new Author(commentAuthorId, commentUsername, commentAvatar, commentGender, commentRemark, commentSigns);

                        String commentContent = commentJson.optString("content", "");
                        String commentCreateTime = commentJson.optString("createTime", "");

                        Comment comment = new Comment(commentId, commentAuthor, commentContent, commentCreateTime);
                        comments.add(comment);
                    }
                }
            }

            boolean likedByCurrentUser = itemJson.optBoolean("likedByCurrentUser", false);

            // 修改构造函数调用，传入Author列表而不是字符串列表
            DynamicItem item = new DynamicItem(id, author, textContent, imageUrls, video, createTime, likers, comments, likedByCurrentUser);
            items.add(item);
        }
        return items;
    }

    private String getToken() {
        SharedPreferences sp = requireActivity().getSharedPreferences("user_prefs", requireContext().MODE_PRIVATE);
        return sp.getString("token", null);
    }
}